<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>垃圾回收时执行回调FinalizationRegistry</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
  </style>
</head>

<body>
  <div class="demo">快回收我呀</div>
</body>
<script>
  "use strict"; {
    const reg = new FinalizationRegistry(value => {
      console.log(`处理啊了吧`)
      console.log(value)
    });
    const demo = document.querySelector(".demo")
    reg.register(demo, "已经被垃圾回收处理了")
    setTimeout(() => {
      document.querySelector(".demo").remove()
    }, 2 * 1000)
  };
</script>

</html>